/**
 * fshows.com
 * Copyright (C) 2013-2019 All Rights Reserved.
 */
package com.example.proxydemo.mycglib;

import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * 自定义类加载器
 *
 * @author Liluqing
 * @version MyClassLoader.java, v 0.1 2019-08-08 13:38
 */
public class MyClassLoader extends ClassLoader{

    private File classPathFile;

    public MyClassLoader(String classPath) {
        this.classPathFile = new File(classPath);
    }

    @Override
    protected Class<?> findClass(String fullClassName) throws ClassNotFoundException {
        if (null != classPathFile) {
            String className = getClassName(fullClassName);
            File classFile = new File(classPathFile, className + ".class");
            if (classFile.exists()) {
                FileInputStream in = null;
                ByteArrayOutputStream out = null;
                try {
                    in = new FileInputStream(classFile);
                    out = new ByteArrayOutputStream();
                    byte[] bytes = new byte[1024];
                    int len;
                    while((len = in.read(bytes)) != -1) {
                        out.write(bytes, 0, len);
                    }
                    return defineClass(fullClassName, out.toByteArray(), 0, out.size());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (null != in) {
                            in.close();
                        }
                        if (null != out) {
                            out.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取类名
     *
     * @param fullClassName
     * @return
     */
    private String getClassName(String fullClassName) {
        String[] strArr = fullClassName.split("\\.");
        return strArr[strArr.length - 1];
    }
}